Functions

As in any other language Python allows for the definition of functions. Functions are a set of sequence of instructions that receive well define inputs and produce some outputs.

To define a function Python uses the word def. The value that the function returns must be preceded by a return. The syntax would be:

def FUNCTION_NAME(INPUTS):
    INSTRUCTIONS
    return OUTPUTS

or

def FUNCTION_NAME(INPUTS):
    INSTRUCTIONS

The return function is optional. Not every function should return an output. Some functions simply modify the inputs without producing any output.

Important: The instructions and the return statements belonging to the fuction must be indented by 4 spaces inside the header. Indentation is the only way that Python has to group lines of code.

Let's have some simple examples


In [ ]:
def square(a):
    return a*a

print(square(1), square(2), square(5))

In [ ]:
square('a') # This should give an error

In [ ]:
def minimum(a, b):
    if a<b:
        return a
    elif b<a:
        return b
    else:
        return a

In [ ]:
minimum(4,5)

In [ ]:
minimum(4,0)

Optional parameters

Functions can have default parameters. These parameters are defined using the syntaxis arg=value, where arg is the argument name and value is the default value for that argument.

Here are some examples


In [ ]:
def power(a, b=2):
    return a**b

In [ ]:
power(2)

In [ ]:
power(2, b=5) # This is the prefered way to change the default parameters

In [ ]:
power(2,5) # This works as well

Exercise 2.1

Define a function distance that takes as arguments two lists a,b and computes the Euclidean distance between the two:

$$ \sqrt{\sum_{i=0}^{N-1} (a_i - b_i)^2} $$

Check your function with these three values

distance([0,0], [1,1])
1.4142135623730951
distance([1,5], [2,2])
3.1622776601683795
distance([0,1,2], [2,3,4])
3.4641016151377544

In [ ]: